package com.smart4j.framework.thread;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * description: 自己实现一个 java.lang.ThreadLocal
 * @version v1.0
 * @author w
 * @date 2018年10月16日下午9:44:59
 **/
public class MyThreadLoacl<T> {
	
	private Map<Thread,T> container = Collections.synchronizedMap(new HashMap<Thread, T>());
	
	public void set(T t){
		container.put(Thread.currentThread(), t);
	}
	
	public T get(){
		Thread thread = Thread.currentThread();
		T value = container.get(thread);
		// 如果value值不存在，且 container 中不存在该线程,则初始化value，并保存
		if(value == null && !container.containsKey(thread)){
			value = initialValue();
			container.put(thread, value);
		}
		return value;
	}

	protected T initialValue() {
		return null;
	}
	
	public void remove(){
		container.remove(Thread.currentThread());
	}
}
